package top.kaoshanji.p1ch04a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch04a-101页a：对方是否可信
 * URL访问地址：/exportRestriction
 * @author kaoshanji
 * ^_^
 * create time 2025/4/3 18:19
 */
public class ExportRestriction extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        // 取得客户端的主机名
        String remoteHost = req.getRemoteHost();
        System.out.println("客户端的主机名：" + remoteHost);

        // 查询客户端是否被允许
        if (!isHostAllowed(remoteHost)) {
            out.println("Access <BLINK>denied</BLINK>");
        } else {
            out.println("Access granted");
        }

    }

    // Disallow hosts ending with .cu, .ir, .iq, .kp, .ly, .sy, and .sd.
    private boolean isHostAllowed(String host) {
        return (!host.endsWith(".cu") &&
                !host.endsWith(".ir") &&
                !host.endsWith(".iq") &&
                !host.endsWith(".kp") &&
                !host.endsWith(".ly") &&
                !host.endsWith(".sy") &&
                !host.endsWith(".sd"));
    }

}
